import React, { createContext, useState, useContext, useEffect, useCallback, useRef } from 'react';
import { getUnreadNotifications } from '@/apis/notification';

const NotificationContext = createContext();

export const NotificationProvider = ({ children }) => {
  const initializedRef = useRef(false);

  const [unreadCount, setUnreadCount] = useState(0);
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [showNotificationCount, setShowNotificationCount] = useState(true);

  useEffect(() => {
    if (!initializedRef.current) {
      const savedIsLoggedIn = localStorage.getItem('isLoggedIn') === 'true';
      setIsLoggedIn(savedIsLoggedIn);

      if (savedIsLoggedIn) {
        const savedCount = localStorage.getItem('unreadNotificationCount');
        setUnreadCount(savedCount ? parseInt(savedCount, 10) : 0);
      }

      const savedSetting = localStorage.getItem('showNotificationCount');
      setShowNotificationCount(savedSetting !== null ? JSON.parse(savedSetting) : true);

      initializedRef.current = true;
    }
  }, []);

  useEffect(() => {
    const updateLocalStorage = () => {
      localStorage.setItem('showNotificationCount', JSON.stringify(showNotificationCount));
      localStorage.setItem('isLoggedIn', isLoggedIn.toString());
      if (isLoggedIn) {
        localStorage.setItem('unreadNotificationCount', unreadCount.toString());
      } else {
        localStorage.removeItem('unreadNotificationCount');
      }
    };

    const rafId = requestAnimationFrame(updateLocalStorage);

    return () => cancelAnimationFrame(rafId);
  }, [showNotificationCount, unreadCount, isLoggedIn]);

  const updateUnreadCount = useCallback(async () => {
    if (!isLoggedIn) return;

    try {
      const notifications = await getUnreadNotifications();
      setUnreadCount(notifications.length);
    } catch (error) {
      console.error('获取未读通知数量失败:', error);
    }
  }, [isLoggedIn]);

  useEffect(() => {
    if (!isLoggedIn) {
      setUnreadCount(0);
      return;
    }

    let isMounted = true;
    const fetchNotifications = async () => {
      if (isMounted) {
        await updateUnreadCount();
      }
    };

    fetchNotifications();
    const timer = setInterval(fetchNotifications, 60000); // 每分钟更新一次

    return () => {
      isMounted = false;
      clearInterval(timer);
    };
  }, [isLoggedIn, updateUnreadCount]);

  const login = useCallback(() => {
    setIsLoggedIn(true);
  }, []);

  const logout = useCallback(() => {
    setIsLoggedIn(false);
    setUnreadCount(0);
    localStorage.removeItem('unreadNotificationCount');
    localStorage.removeItem('isLoggedIn');
  }, []);

  const toggleShowNotificationCount = useCallback((value) => {
    setShowNotificationCount(prev => {
      const newValue = value !== undefined ? value : !prev;
      localStorage.setItem('showNotificationCount', JSON.stringify(newValue));
      return newValue;
    });
  }, []);

  return (
    <NotificationContext.Provider value={{ 
      unreadCount, 
      updateUnreadCount, 
      login, 
      logout, 
      showNotificationCount, 
      toggleShowNotificationCount,
      isLoggedIn
    }}>
      {children}
    </NotificationContext.Provider>
  );
};

export const useNotification = () => {
  const context = useContext(NotificationContext);
  if (context === undefined) {
    throw new Error('useNotification must be used within a NotificationProvider');
  }
  return context;
};